package mysql

import (
	"novel/novelrpc/novelrpc"

	"gorm.io/gorm"
)

type Novel struct {
	gorm.Model
	UserId    int64  `gorm:"type:int(11);not null"`
	Title     string `gorm:"type:varchar(30);not null"`
	NovelType string `gorm:"type:varchar(30);not null"`
	Label     string `gorm:"type:varchar(50);not null"`
	Content   string `gorm:"type:varchar(200);not null"`
}

func (n *Novel) NovelAdd(db *gorm.DB) error {
	return db.Debug().Create(n).Error
}

func (n *Novel) FirstNovelById(db *gorm.DB, NovelId int64) error {
	return db.Debug().Where("id=?", NovelId).First(n).Error
}

func NovelList(db *gorm.DB, in *novelrpc.NovelListRequest) []*novelrpc.NovelList {
	/*
		SELECT
		  *
		FROM
		  novels
		  LEFT JOIN users ON novels.user_id = users.id
	*/
	var list []*novelrpc.NovelList
	tx := db.Debug().Model(&Novel{}).Select("novels . *, users.head_image,  users.nick_name").
		Joins("LEFT JOIN users ON novels.user_id = users.id").
		Scopes(Paginate(int(in.Page), int(in.Size))).Order("novels.created_at desc")
	if in.Title != "" {
		tx.Where("novels.title=?", in.Title)
	}
	if in.NovelType != "" {
		tx.Where("novels.novel_Type=?", in.NovelType)
	}
	tx.Find(&list)
	return list
}
